package com.lvmama.pangolin.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
public class SpringContextUtil implements ApplicationContextAware{
	/**  
	* @Title：SpringContextUtil.java
	* @Author:zhoutianqi
	* @Description:
	* @Date：2017年2月16日上午9:35:51  
	*/
	private ApplicationContext applicationContext; 
	
	/** 
     * 取得存储在静态变量中的ApplicationContext. 
     */ 
    
    public ApplicationContext getApplicationContext() {  
        checkApplicationContext();  
        return applicationContext;  
    }
  
    /** 
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. 
     */  
    @SuppressWarnings("unchecked")  
    public <T> T getBean(String name) {  
        checkApplicationContext();  
        return (T) applicationContext.getBean(name);  
    }  
  
    /** 
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. 
     */  
    @SuppressWarnings("unchecked")  
    public <T> T getBean(Class<T> clazz) {  
        checkApplicationContext();  
        return (T) applicationContext.getBeansOfType(clazz);  
    }  
    /** 
     * 清除applicationContext静态变量. 
     */  
    public void cleanApplicationContext() {  
        applicationContext = null;  
    }  
  
    private void checkApplicationContext() {  
        if (applicationContext == null) {  
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");  
        }  
    }

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext=applicationContext;
		
	}  
}
